<template>
    <div class="container" :style="{minHeight: screenHeight}">
      <div class="sportType">
        <p>运动类型：</p>
        <input type="text" v-model="sportTypeValue" placeholder="请输入运动类型" placeholder-style="font-size:28rpx;color:#CCCCCC;">
      </div>
      <textarea v-model="goalValue" placeholder="请输入本次运动的目标/心情（100字以内）" placeholder-style="font-size:28rpx;color:#CCCCCC;" maxlength="100"></textarea>
      <div class="addPic">
        <div class="picBox">
          <div class="pics" v-for="(item,index) in imgFileList" :key="index" @longtap="cencelPic(index)">
            <img :src="item">
          </div>
          <div class="addPicbtn" @click="fnchangePic" v-if="imgFileList.length < 3">
            <img src="../../../static/image/icon-add.png">
          </div>
        </div>
        <p>{{ number }}/3</p>
      </div>
      <div class="sure-btn" @click="fnSure">
        <p>完成</p>
      </div>
      <i-message id="message" />
    </div>
</template>
<script>
  const { $Message } = require('../../../static/iview/base/index');
    export default {
        name: '',
        data(){
            return {
              AuthorizationStr:'',  //接口的请求头信息
              sportTypeValue:'',   //运动类型的输入值
              screenHeight: (Number(wx.getSystemInfoSync().windowHeight)) + 'px',
              goalValue:'',   //目标值
              number:0,  //选择的照片张数
              imgFileList:[],   //显示图片地址数组
              imgUploadList:[],   //微信选择图片地址存储数组
              picIndex:0,   //上传到第几张图片
              upLoadimgFileList:[],   //上传到后台的图片地址
              requestFileList:[],     //后台返回的图片地址
              requestImgDelId:[],     //删除图片的ID
              isChooseImg:false,      //用户是否选择了图片
              addUrl:'/sign/insertSign',    //默认接口为添加
              id:'',     //签卡详情ID
            }
        },
      methods:{
        fnSure(){
            if(!this.sportTypeValue){
              $Message({
                content: '请输入运动类型',
                type: 'error'
              });
              return false;
            }
          if(!this.goalValue){
            $Message({
              content: '请输入请输入本次运动的目标/心情',
              type: 'error'
            });
            return false;
          }
          wx.showLoading({
            title: '加载中' // 数据请求前loading
          });
          //上传图片
          if(this.isChooseImg){
            this.upLoadPic();
          } else {
            this.uploadMessage();
          }
        },

        //往服务器上传图片
        upLoadPic(){
            let that = this;
            if(this.picIndex + 1 <= this.imgUploadList.length){
              wx.uploadFile({
                url: this.$baseURL + '/file/insertFile',
                filePath: this.imgUploadList[this.picIndex],
                name: 'file',
                header:{
                  'Authorization' : this.AuthorizationStr
                },
                success (res){
                  console.log(res);
                  if(JSON.parse(res.data).code == 0){
                    that.upLoadimgFileList.push(JSON.parse(res.data).data);
                    that.picIndex ++;
                    that.upLoadPic();
                  } else {
                    wx.hideLoading();
                    $Message({
                      content: '加载失败',
                      type: 'error'
                    });
                  }
                }
              })
            } else {
              this.picIndex = 0;
              this.uploadMessage();
            }
        },

        //最终上传图片和文字
        uploadMessage(){
          this.$httpWX.post({
            url: this.addUrl,
            data: {
              id:this.id,
              type:this.sportTypeValue,
              content:this.goalValue,
              fileList:this.upLoadimgFileList,
              delFileIdList:this.requestImgDelId
            }
          }).then(res => {
            if(res.code == 0){
              wx.hideLoading();
              $Message({
                content: '签卡成功',
                type: 'success'
              });
              setTimeout(function () {
                wx.switchTab({
                  url: '../index/main'
                })
              },2000)
            }
          });
        },

        //选择上传图片
        fnchangePic(){
          let that = this;
          wx.chooseImage({
            count: 3,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success (res) {
              that.isChooseImg = true;
              that.number+=res.tempFilePaths.length;
              res.tempFilePaths.forEach((val)=>{
                that.imgUploadList.push(val);
                that.imgFileList.push(val);
              });
            }
          })
        },

        //长按删除照片
        cencelPic(index){
          let that = this;
          wx.showModal({
            title: '提示',
            content: '确定要删除该照片？',
            success (res) {
              if (res.confirm) {
                that.imgFileList.splice(index,1);
                that.number--;
                that.requestImgDelId.push(that.requestFileList[index].id);
                that.requestFileList.splice(index,1);
              } else if (res.cancel) {
              }
            }
          })
        },

        //获取签到详情
        getDetail(id){
          console.log("我进来了");
          this.$httpWX.get({
            url: '/sign/getSignDetail',
            data: {
              id:id
            }
          }).then(res => {
            console.log(res);
            //回显运动类型
            this.sportTypeValue = res.data.type;
            //回显运动目标
            this.goalValue = res.data.content;
            //回显图片
            this.imgFileList = [];
            this.number = res.data.fileList.length;
            res.data.fileList.forEach((val)=>{
              this.imgFileList.push(val.webPath)
            });
            //存储后台返回的图片数组
            this.requestFileList = res.data.fileList;
          });
        }
      },
      mounted(){

        //页面参数
        let options = this.$getOptions();
        if(options.type === 'edit'){
          this.getDetail(options.id);
          this.id = options.id;
          this.addUrl = '/sign/updateSign';
        } else {
          this.addUrl = '/sign/insertSign';
          this.id = '';
        }

        //重置图片上传数组
        this.imgUploadList = [];

        //拼装请求头
        let token = wx.getStorageSync("token");
        let userInfo = wx.getStorageSync("userInfo");
        if(token){
          this.AuthorizationStr = "TOKEN_" + token;
        }
        if(userInfo && userInfo != undefined && userInfo.id){
          if(this.AuthorizationStr){
            this.AuthorizationStr += ","
          }
          this.AuthorizationStr += "userId_" + userInfo.id;
        }
      }
    }
</script>

<style>
  .container{
    width: 100%;
    background-color: #F7F7F7;
    position: relative;
    box-sizing: border-box;
    overflow: hidden;
  }
  .sportType{
    width: 95%;
    height: 90rpx;
    margin: 0 auto;
    padding: 0 40rpx;
    display: flex;
    align-items: center;
    background-color: white;
    border-bottom: 1rpx solid #EEEEEE;
  }
  .sportType>p{
    height: 55rpx;
    font-size: 30rpx;
    color: #CCCCCC;
    margin-right: 20rpx;
    line-height: 55rpx;
  }
  .sportType>input{
    flex: 1;
    font-size: 28rpx;
    color: #282828;
  }
  textarea{
    width: 100%;
    height: 320rpx;
    background-color: white;
    font-size: 28rpx;
    box-sizing: border-box;
    padding: 28rpx 40rpx;
    color: #282828;
  }

  /*上传图片样式*/
  .addPic{
    width: 100%;
    box-sizing: border-box;
    padding: 5%;
    margin: 0 auto;
    background-color: white;
  }
  .picBox{
    display: flex;
  }
  .pics{
    width: 212rpx;
    height: 161rpx;
    margin-right: 10rpx;
  }
  .pics>img{
    width: 100%;
    height: 100%;
  }
  .addPic>p{
    font-size:24rpx;
    font-weight:400;
    color:rgba(153,153,153,1);
    line-height:44rpx;
    text-align: right;
  }
  .addPicbtn{
    width: 212rpx;
    height: 161rpx;
    background:rgba(229,229,229,1);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .addPicbtn>img{
    width: 56rpx;
    height: 56rpx;
  }
  .sure-btn{
    width: 88%;
    height:90rpx;
    background:rgba(36,198,138,1);
    border-radius:10rpx;
    margin: 40rpx auto;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .sure-btn>p{
    font-size: 30rpx;
    font-weight: 400;
    color: white;
  }
</style>
